package rexsee.cartoon.gif;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

import rexsee.cartoon.CartoonView;
import rexsee.core.style.CanvasSheet;
import rexsee.core.utilities.Utilities;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;

public class GifView extends CartoonView {

	private GifDecoder decoder = null;
	private float speedFactor = 1;
	private int currentIndex = -1;

	public GifView(Context context) {
		super(context);
	}

	public void setGif(final String gifPath, final ScaleType scaleType, final CanvasSheet style, final Runnable onParseStart, final Runnable onParseReady) {

		if (gifPath == null) {
			Toast.makeText(getContext(), "Null path.", Toast.LENGTH_LONG).show();
			return;
		}
		String check = gifPath.toLowerCase().trim();
		if (!check.endsWith(".gif") || !check.startsWith("file://")) {
			Toast.makeText(getContext(), "Invalid path.", Toast.LENGTH_LONG).show();
			return;
		}
		if (check.startsWith("file://")) {
			File file = new File(Uri.parse(gifPath).getPath());
			if (!file.exists() || !file.isFile()) {
				Toast.makeText(getContext(), "Gif does not exist.", Toast.LENGTH_LONG).show();
				return;
			}
		}

		destroy();

		if (onParseStart != null) onParseStart.run();
		new Thread() {
			@Override
			public void run() {
				decoder = new GifDecoder();

				FileInputStream is;
				try {
					is = new FileInputStream(new File(Uri.parse(gifPath).getPath()));
					decoder.read(is);
				} catch (Exception e) {
					Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
					return;
				}

				speedFactor = Utilities.getFloat(style.factor, 1.0f);

				add(new CartoonInterface() {
					@Override
					public ArrayList<CartoonUnit> getUnits(CartoonView view) {

						if (decoder == null) return null;

						currentIndex++;
						if (currentIndex < 0 || currentIndex > decoder.getFrameCount() - 1) currentIndex = 0;

						Bitmap bitmap = decoder.getFrame(currentIndex);
						int delay = (int) (decoder.getDelay(currentIndex) * speedFactor);

						Rect rect;
						if (scaleType.equals(ScaleType.CENTER_INSIDE)) {
							float scale = Math.min(view.getWidth() / (float) bitmap.getWidth(), view.getHeight() / (float) bitmap.getHeight());
							int w = (int) (bitmap.getWidth() * scale);
							int h = (int) (bitmap.getHeight() * scale);
							int top = (view.getHeight() - h) / 2;
							int left = (view.getWidth() - w) / 2;
							rect = new Rect(left, top, left + w, top + h);
						} else {
							rect = new Rect(0, 0, view.getWidth(), view.getHeight());
						}

						CartoonUnit unit = new CartoonUnit();
						unit.bitmap = bitmap;
						unit.srcRect = new Rect(0, 0, unit.bitmap.getWidth(), unit.bitmap.getHeight());
						unit.targetRect = rect;
						unit.autoRecycle = false;

						ArrayList<CartoonUnit> rtn = new ArrayList<CartoonUnit>();
						rtn.add(unit);

						setInterval(delay);

						return rtn;

					}
				});

				//browser.progressDialog.hide();
				if (onParseReady != null) onParseReady.run();
				play();
			}
		}.start();

	}

	public void destroy() {
		stop();
		clear();
		if (decoder != null) {
			try {
				decoder.destroy();
				decoder = null;
			} catch (Error err) {
			} catch (Exception e) {
			}
		}
	}

}
